﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Diagnostics;
using FuelTracker.Models;
using FuelTracker.DataAccess;

namespace FuelTracker.Services
{
    public class StorageService : IStorageService
    {
        private IVehicleDao vehicleDao;

        private List<VehicleInfo> vehicleInfos;
        public IEnumerable<VehicleInfo> VehicleInfos
        {
            get
            {
                if (vehicleInfos == null)
                    vehicleInfos = vehicleDao.LoadVehicleInfos().ToList();

                return vehicleInfos;
            }
        }

        public StorageService(IVehicleDao vehicleDao)
        {
            this.vehicleDao = vehicleDao;
        }

        public Vehicle GetLastVehicle()
        {
            Stopwatch w = new Stopwatch();
            w.Start();

            Guid id = vehicleDao.LoadLastVehicleId();
            if (id == Guid.Empty)
                return null;

            Vehicle vehicle = vehicleDao.LoadVehicle(id);

            w.Stop();
            Debug.WriteLine("GetLastVehicle: " + w.ElapsedMilliseconds);

            return vehicle;
        }

        public void SaveLastVehicle(Vehicle vehicle)
        {
            vehicleDao.SaveLastVehicleId(vehicle.Id);
        }

        public void AddVehicle(Vehicle vehicle)
        {
            vehicleDao.SaveVehicle(vehicle);
            vehicleInfos.Add(new VehicleInfo
                {
                    Id = vehicle.Id,
                    Name = vehicle.Name
                });
            vehicleDao.SaveVehicleInfos(vehicleInfos);
            vehicleDao.SaveLastVehicleId(vehicle.Id);
        }

        public void SaveVehicle(Vehicle vehicle)
        {
            Stopwatch w = new Stopwatch();
            w.Start();

            vehicleDao.SaveVehicle(vehicle);
            vehicleDao.SaveLastVehicleId(vehicle.Id);

            w.Stop();
            Debug.WriteLine("SaveVehicle: " + w.ElapsedMilliseconds);
        }
    }
}
